How to creat svg document with SVG.js

Home

Get source code at Github

Content【目录】


A few days ago, I got stuck in the mud of creating a svg dom with SVG.js. After many test and searching, I found out that someting is different from the official manual.

The "Uncaught TypeError" problem of using SVG.js

For example, we write some dom in .html like this:
          <!DOCTYPE html> 
<html>
<head>
<title>Creating SVG with SVG.js</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script src="https://cdn.bootcss.com/svg.js/3.0.11/svg.min.js"></script>
</head>
<body>
<div id="drawing"></div>
<script>
// write down your javascript here..
</script>
</body>
</html>

The official manual said that <script>...</script> part like this:

          var draw = SVG('drawing').size(300, 300) 
var rect = draw.rect(100, 100).attr({ fill: '#f06' })

The script above pass throught on jsfiddle.net test. However, it doesn't work on my case, no matter running on my msie 7.0 to 11.0 or chrome 58. It crashed like this:

Uncaught TypeError: Cannot read property 'size' of null

I felt so depressed that even could not got sleep for two whole days, then I found the official example only working under v3.0, such as v2.7.1.

The way to write svg.js script and DOM

After many tests and searching, I found out that these code running on svg.js after v3.0:

Style 1

    DOM:       <div id="drawing"> </div>

    Script 1:     var draw = SVG().addTo('#drawing').size(1024,200);

or  Script 2:     var draw = SVG().addTo('#drawing').size('100%', '100%');

Style 2

    DOM:       <div class="drawing"> </div>

    Script 1:     var draw = SVG().addTo('.drawing').size(1024,200);

or  Script 2:     var draw = SVG().addTo('.drawing').size('100%', '100%');

Style 3

    DOM:       <svg id="drawing"> </svg>

    Script 1:     var draw = SVG('#drawing').size(1024, 200);

or  Script 2:     var draw = SVG('#drawing').size('100%', '100%');


Read my code here, you can get more by reading html source code.


Done!!!